# -*- coding:utf8 -*-
import os
from django.core.management.base import BaseCommand, CommandError
from django.utils.importlib import import_module
import MySQLdb

__author__ = 'Forcs'

class Command(BaseCommand):

    DATABASE_CONFIG = {
        'ROOT': ('', ''),
        'USER': '',
        'PASSWORD': '',
        'NAME': '',
        'HOST': 'localhost',
        'PORT': 3306,
        'GRANT': '*',
        'CHARSET': 'utf8',
        'COLLATE': 'general_ci'
    }

    def handle(self, *args, **options):
        db_config = self.DATABASE_CONFIG
        try:
            settings = import_module(os.environ['DJANGO_SETTINGS_MODULE'])
            db_config.update(getattr(settings, 'DATABASE_CONFIG'))
            root = db_config['ROOT']
            root_name = root[0]
            root_password = root[1]
            db_host = db_config['HOST']
            db_port = db_config['PORT']
            conn = MySQLdb.connect(host=db_host, port=db_port, user=root_name, passwd=root_password)
            cursor = conn.cursor()
            db_name = db_config['NAME']
            db_charset = db_config['CHARSET']
            db_collate = '%s_%s' % (db_charset, db_config['COLLATE'])
            cursor.execute('CREATE DATABASE %s DEFAULT CHARACTER SET %s COLLATE %s' % (db_name, db_charset, db_collate))
            if db_config['USER'] != root_name:
                grant = db_config['GRANT'] if 'GRANT' in db_config.keys() else 'ALL'
                if isinstance(grant, list):
                    grant = ','.join(grant)
                elif grant == '*':
                    grant = 'ALL'
                cursor.execute('GRANT %s ON %s.* TO \'%s\'@\'%s\' IDENTIFIED BY \'%s\'' %
                               (grant, db_name, db_config['USER'], db_host, db_config['PASSWORD']))
            cursor.close()
        except Exception as e:
            raise CommandError(str(e))
